//
//  LoginViewController.m
//  iModern
//
//  Created by 张义帅 on 15/7/1.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

#import "LoginViewController.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialAccountManager.h"
#import "WXApi.h"
#import "MobClick.h"
#import "iModern-Swift.h"

@interface LoginViewController ()

@property(nonatomic, weak) UITextField *tfUserName;
@property(nonatomic, weak) UITextField *tfPassword;
@property(nonatomic, weak) UIButton    *button;
@property(nonatomic, weak) UIButton    *button2;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    AppDelegate *appDelegates = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    appDelegate = appDelegates;
    [super viewDidLoad];
    self.title = @"登录";
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewLogoCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LOGO"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewUserNameCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"USER_NAME"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewPasswordCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"PASSWORD"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewLoginCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LOGIN"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewSSOCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SSO"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginViewForgotCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"FORGOT"];
    
    [self.tableView setSeparatorColor:[UIColor clearColor]];
    [self initBackButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LoginView"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LoginView"];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [UITableViewCell new];
    
    switch (indexPath.row)
    {
        case 0:
            cell = [tableView dequeueReusableCellWithIdentifier:@"LOGO" forIndexPath:indexPath];
            break;
        case 1:
            cell = [tableView dequeueReusableCellWithIdentifier:@"USER_NAME" forIndexPath:indexPath];
            self.tfUserName = (UITextField *) [cell viewWithTag:20];
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:@"PASSWORD" forIndexPath:indexPath];
            self.tfPassword = (UITextField *) [cell viewWithTag:20];
            break;
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:@"FORGOT" forIndexPath:indexPath];
        case 4:
            cell = [tableView dequeueReusableCellWithIdentifier:@"LOGIN" forIndexPath:indexPath];
            break;
        case 5:
            cell = [tableView dequeueReusableCellWithIdentifier:@"SSO" forIndexPath:indexPath];
            self.button = (UIButton *) [cell viewWithTag:30];
            [self.button addTarget:self action:@selector(sinaLogin) forControlEvents:(UIControlEventTouchUpInside)];
            
            self.button2 = (UIButton *) [cell viewWithTag:20];
            [self.button2 addTarget:self action:@selector(wechatLogin) forControlEvents:(UIControlEventTouchUpInside)];
            if (![WXApi isWXAppInstalled])
            {
                self.button2.hidden = YES;
                //int swidth = [[UIScreen mainScreen] bounds].size.width;
                //self.button.frame = CGRectMake(swidth/2-self.button.frame.origin.x/2, self.button.frame.origin.y, self.button.frame.size.width, self.button.frame.size.height);
            }
            else
            {
                self.button2.hidden = NO;
            }
            break;
            
        default:
            cell = nil;
            break;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
    switch (indexPath.row)
    {
        case 0:
            height = (self.view.frame.size.width) / 2;
            break;
        case 4:
            height = 80;
            break;
        case 5:
            height = 120;
            break;
        default:
            height = 40;
            break;
    }
    return height;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 1 || indexPath.row > 2)
    {
        [self.view endEditing:YES];
        if (indexPath.row == 4)
        {
            NSString *userName = self.tfUserName.text;
            NSString *password = self.tfPassword.text;
            [self login:userName information:password];
        }
    }
    //    if (indexPath.row == 3)
    //    {
    //        ForfotFormViewController *forgot = [ForfotFormViewController new];
    //        [self.navigationController pushViewController:forgot animated:YES];
    //    }
    
}

- (void)login:(NSString *)userName information:(NSString *)password
{
    //    appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    [self.view endEditing:YES];
    ResultSet *rs = [appDelegate.contactManager loginWithUserName:userName andPassword:password];
    if (rs == nil)
    {
        [self alertNetworkConnectionException];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else
    {
        if (![rs hasErrors] && ![rs isEmpty])
        {
            [self alertSuccessMessage:@"登录成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Login Successful" object:nil];
            [appDelegate.navigationController popToRootViewControllerAnimated:YES];
            //            [self.navigationController popViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh Shop" object:nil];
        }
        else
        {
            [self alertErrorMessage:rs.errorMessage];
        }
    }
    
}

- (void)wechatLogin
{
    
    if ([WXApi isWXAppInstalled])
    {
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
        
        snsPlatform.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response)
                                      {
                                          
                                          if (response.responseCode == UMSResponseCodeSuccess)
                                          {
                                              
                                              UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToWechatSession];
                                              
                                              NSDictionary *params = [NSMutableDictionary new];
                                              [params setValue:snsAccount.userName forKey:@"nickname"];
                                              [params setValue:snsAccount.usid forKey:@"openid"];
                                              [params setValue:snsAccount.iconURL forKey:@"headimgurl"];
                                              
                                              if (params)
                                              {
                                                  [MobClick event:@"wxLogin"];
                                                  appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
                                                  ResultSet *rs = [appDelegate.contactManager loginWithWeChat:params];
                                                  if (rs && ![rs hasErrors] && ![rs isEmpty])
                                                  {
                                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"Login Successful" object:nil];
                                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh" object:nil];
                                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh Shop" object:nil];
                                                      appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
                                                      [appDelegate.navigationController popToRootViewControllerAnimated:YES];
                                                  }
                                                  else
                                                  {
                                                      [self alertErrorMessage:@"网络连接异常，请检查你的网络设置"];
                                                  }
                                                  
                                              }
                                              else
                                              {
                                                  [self alertErrorMessage:@"获取用户信息失败"];
                                              }
                                              
                                          }
                                          
                                      });
        
    }
    else
    {
        [self alertErrorMessage:@"您没有安装微信，请换一种登录方式。"];
    }
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh Shop" object:nil];
    
}

- (void)sinaLogin
{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self, [UMSocialControllerService defaultControllerService], YES, ^(UMSocialResponseEntity *response)
                                  {
                                      
                                      if (response.responseCode == UMSResponseCodeSuccess)
                                      {
                                          
                                          UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                                          NSDictionary          *params     = [NSMutableDictionary new];
                                          
                                          [params setValue:snsAccount.userName forKey:@"name"];
                                          [params setValue:snsAccount.usid forKey:@"id"];
                                          [params setValue:snsAccount.iconURL forKey:@"avatar_hd"];
                                          
                                          if (params)
                                          {
                                              [MobClick event:@"wbLogin"];
                                              
                                              ResultSet *rs = [appDelegate.contactManager loginWithWeibo:params];
                                              if (rs && ![rs hasErrors] && ![rs isEmpty])
                                              {
                                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"Login Successful" object:nil];
                                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh" object:nil];
                                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh Shop" object:nil];
                                                  [appDelegate.navigationController popToRootViewControllerAnimated:YES];
                                              }
                                              else
                                              {
                                                  [self alertErrorMessage:@"网络连接异常，请检查你的网络设置"];
                                              }
                                              
                                          }
                                          else
                                          {
                                              [self alertErrorMessage:@"获取用户信息失败"];
                                          }
                                      }
                                      
                                  });
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"Refresh Shop" object:nil];
    
}

@end
